package dao;

import domain.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import utils.DruidUtils;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class DbOps {
    public static List<Object[]> getUsers() {
        QueryRunner qR = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select * from user limit 1000";

        List<Object[]> query = null;
        try {
            query = qR.query(sql, new ArrayListHandler());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    public static void addUser(User usr) {
        QueryRunner qR = new QueryRunner(DruidUtils.getDataSource());
        String sql = "insert into user values(?,?,?,?,?)";
        Object[] param = {null, usr.getUsername(), usr.getPassword(), usr.getSex(), usr.getBirthday()};
        try {
            qR.update(sql, param);
            System.out.println("添加成功");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("添加失败");
        }
    }

    public static boolean validateUser (String username,String password) {
        QueryRunner qR = new QueryRunner(DruidUtils.getDataSource());
        String sql = "SELECT COUNT(1) FROM USER WHERE USERNAME=? AND PASSWORD=?";
        Object[] param = {username,password};
        long query = 0;
        try {
            query = qR.query(sql, new ScalarHandler<>(), param);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query == 1;
    }

    public static void main(String[] args) throws SQLException {
        List<Object[]> users = getUsers();
        for (Object[] ele:users) {
            System.out.println(Arrays.toString(ele));
        }

        System.out.println(validateUser("admin", "123456"));
        System.out.println(validateUser("ff", "123456"));
        //addUser(new User(7, "管理员", "654321", "女", "2010-01-01"));
        //users = getUsers();
        //System.out.println(Arrays.toString(users));

    }
}
